import { Component, OnInit, Injector, Input } from '@angular/core';
import { ResourceClassifyTreeComponent } from '../resource-classify-tree/resource-classify-tree.component';
import { TreeNode } from 'primeng/primeng';
import { SELECT_MULTIPLE_VALUE_ACCESSOR } from '@angular/forms/src/directives/select_multiple_control_value_accessor';
import { daLocale } from 'ngx-bootstrap';
@Component({
  selector: 'app-resource-classify-tree-with-data',
  templateUrl: './resource-classify-tree-with-data.component.html',
  styleUrls: ['./resource-classify-tree-with-data.component.css']
})
export class ResourceClassifyTreeWithDataComponent extends ResourceClassifyTreeComponent implements OnInit {

  constructor(
    injector: Injector
  ) {
    super(injector)
  }
  expressionError = false
  ngOnInit() {
    super.ngOnInit()
  }

  @Input() set selectedIds(ids: Array<string>) {
    //console.log(ids,this.data)
    ids = Array.from(new Set(ids))
    if(!ids){
      this.selectedFiles = [];
      return;
    }
    if(ids.length == 0){
      this.selectedFiles = [];
      return
    }
    let selection = [];
    for (let id of ids) {
      let result;
      if(this.data){
        result = this.findInTree(this.data, id , "resCategoryId");
      }
      
      //如果找得到树节点
      //&& (!selection.includes(this.result))
      if(result && (!selection.includes(result))){
        selection.push(result)
        // 找出父节点，如果有加入数组
        this.selectParent(result, selection)
      }
    }
    this.selectedFiles = selection;
    this.selectedFilesChange.emit(this.selectedFiles)
    //this.expandAllOnlyWithSelected(ids)
    //console.log(this.data,selection)
  }
  nodeSelect($event) {
    super.nodeSelect($event);
  }

  //选中父类
  selectParent(treeNode,selection){
    //console.log(treeNode)
    if(treeNode.parent){
      //排除相同的
      if(!selection.includes(treeNode.parent)){
        treeNode.parent.expanded = true;
        selection.push(treeNode.parent);
        this.selectParent(treeNode.parent, selection);
      }
    }else{
      this.up(treeNode,selection);
    }
  }

  //第一次向上查找
  public up(treeNode,selection){
    for(let item of this.data){
      if(item.children){
        if(treeNode.parentId == item.data){
          if(!selection.includes(treeNode)){
            treeNode.expanded = true;
            selection.push(treeNode)
          }  
        }
        if(treeNode.parentId != "0"){
          let data = this.findInTree(this.data, treeNode.parentId , "resCategoryId");
          if(!selection.includes(data)){
            data.expanded = true;
            selection.push(data)
          } 
          this.up(data,selection)
        }else{
          return selection;
        }
      }
      
    }
  }

}
